<template>
  <el-dialog :visible.sync="dialogVisible" title="新增销售订单" width="1400px" :close-on-click-modal="false" v-drag2anywhere>
    <el-form :model="formData" ref="formData" label-width="120px" :rules="rules" size="mini">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="下单时间:" prop="orderdate">
            <el-date-picker v-model="formData.orderdate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="外部单号:" prop="ordercode">
            <el-input v-model="formData.ordercode" placeholder="订单编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单渠道:" prop="platformid">
            <el-select v-model="formData.platformid" placeholder="请选择订单类型" @change="handlePlatformChange">
              <el-option v-for="(item,index) in platforms" :key="index" :value="item.id"
                :label="item.label"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="渠道点位:" prop="platformrate">
            <el-input-number v-model="formData.platformrate" style="width: 120px;" :step="0.01" :min="0" :max="1"
              @change="handleUpdateRmb">
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="合作商名称:" prop="supname">
            <el-select v-model="formData.supname" style="width: 100%;" @change="handleSupChange">
              <el-option v-for="(item,index) in suppliers" :label="item.name" :key="item.index" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合作商点位(%):" prop="suprate">
            <el-input-number v-model="formData.suprate" style="width: 120px;" :step="0.01" :min="0"
              @change="handleUpdateRmb" :max="1">
              <span slot="suffix">%</span>
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <span style="color:darkgrey;">说明: {{formData.supratememo}}</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="客户地区:" prop="region_ids">
            <el-cascader ref="cityregion" props.expandTrigger="hover" :options="regionList"
              v-model="formData.region_ids" :props="{value:'region_id',label:'region_name'}"
              @change="handleRegionChange" placeholder="请选择地区">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货人:" prop="buyerinfo">
            <el-select v-model="formData.buyer" filterable placeholder="客户姓名" @change="handleClientChanged" allow-create
              style="width: 100%;" clearable>
              <el-option v-for="(item,index) in clients" :key="item.id" :label="item.username"
                :value="{value:item,label:item.username}" :title="item.keyword"
                style="height: 50px; width: 300px;border-bottom: 1px solid #f7f8f8;">
                <div style="clear: both; padding: 0px; position: absolute; ">{{item.username}}</div>
                <div style="position: absolute;right: 10px;color: #bfbfbf; ">{{item.mobile}}</div>
                <div style="clear: both; padding: 0px; color: #bfbfbf; font-size: 12px; position: absolute;top:20px">
                  {{ item.address }}
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话:" prop="mobile">
            <el-input placeholder="联系电话" v-model="formData.mobile"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际客户:" prop="client">
            <el-autocomplete v-model="formData.client" placeholder="实际客户" :fetch-suggestions="querySearchAsync"
              style="width: 100%;"></el-autocomplete>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址:" prop="address">
            <el-input v-model="formData.address" placeholder="收货详细地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务员:" prop="saleman">
            <el-select v-model="formData.saleman" placeholder="业务员姓名">
              <el-option v-for="(item,index) in salelist" :label="item.name" :value="item.name"
                :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="客户单位:" prop="clientname">
            <el-input v-model="formData.clientname" placeholder="客户单位名称" :title="formData.clientname"
              clearable></el-input>
          </el-form-item>
        </el-col>


      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="清单明细">
            <div style="text-align: right; margin-bottom: 5px;">
              <el-button-group>
                <el-button type="primary" size="mini" icon="el-icon-plus"
                  @click="handleImportBoughtGood" :disabled="true">从采购记录添加</el-button>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleImportGood">从产品库添加</el-button>
              </el-button-group>
              <GoodFilter v-if="goodfilterVisible" ref="goodFilterUI" @selectHandler="handleGoodSelect">
              </GoodFilter>
              <BuyListUI ref="buylistUI" v-if="buylistVisible" @completeHandler="handleImportBoughtGoodCallback"></BuyListUI>

            </div>
            <div style="height: 300px; overflow-y: auto;">
              <el-table :data="tableData" border height="100%">
                <el-table-column type="index" label="序号" align="center"></el-table-column>
                <el-table-column prop="platform" label="渠道" align="center" width="120px"
                  show-overflow-tooltip></el-table-column>
                <el-table-column prop="sn" label="商品编码" align="center" width="120px"></el-table-column>
                <el-table-column prop="title" label="商品名称" width="200px" show-overflow-tooltip></el-table-column>
                <el-table-column prop="model" label="规格型号" show-overflow-tooltip></el-table-column>

                <el-table-column prop="unit" label="单位" width="100px" align="center" show-overflow-tooltip>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.unit" style="width: 100%;">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="count" label="数量" align="center" width="110px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.count" style="width: 100%;" @change="handleUpdateRmb">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="单价" width="120px" align="center">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.price" style="width: 100%;" @change="handleUpdateRmb"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="总价" width="120px" align="center">
                  <template v-slot="scope">{{format2Number(scope.row.total,NUMBER_DIGITS)}}</template>
                </el-table-column>
                <el-table-column prop="supprice" label="折扣单价" width="100px" align="center">
                  <template v-slot="scope">{{format2Number(scope.row.supprice,NUMBER_DIGITS)}}</template>
                </el-table-column>
                <el-table-column prop="suptotal" label="折扣小计" width="100px" align="center">
                  <template v-slot="scope">{{format2Number(scope.row.suptotal,NUMBER_DIGITS)}}</template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="80px">
                  <template v-slot="scope">
                    <el-button size="mini" circle icon="el-icon-delete" type="danger"
                      @click="handleRemoveGood(scope.$index,scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div style="text-align: right; padding-right: 10px; margin-top: 10px;">
              <span style="width:200px; margin-right: 30px;">订单总额: {{format2Number(sum_order,NUMBER_DIGITS)}}</span>
              <span style="width:200px; margin-right: 30px;">应收总额: {{format2Number(sum_platform,NUMBER_DIGITS)}}</span>
              <span style="width:200px;">折后总额: {{format2Number(sum_sup,NUMBER_DIGITS)}}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="销售合同:">
            <div style="margin: 5px 0px;">需要上传销售合同(双方公章)。</div>
            <el-upload list-type="picture-card" ref="upload" :file-list="upconfig.imgList" :action="upconfig.action"
              :headers="upconfig.headers" :accept="upconfig.accept" :limit="upconfig.limit" :on-change="handleChange"
              :auto-upload="false" :on-remove="handleRemove" :on-exceed="handleLimit" multiple
              :on-preview="handlePreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单备注:">
            <el-input type="textarea" rows="5" v-model="formData.ordermemo" placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import GoodFilter from './goodsfilter.vue';
  import BuyListUI from './buylist.vue';
  export default {
    components: {
      GoodFilter,
      BuyListUI
    },
    data() {
      var validatejdrate = (rule, value, callback) => {
        if (value == 0) {
          callback(); ///new Error("折扣率不能为0")
        } else {
          callback();
        }
      };
      return {
        NUMBER_DIGITS:4,
        buylistVisible: false,
        //文件上传相关变量
        upconfig: {
          //文件上传相关参数
          accept: '.jpg,.jpeg,.png,.pdf,.doc,.docx',
          limit: 5,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          rids: [], //要删除的id
          action: ""
        },
        goodfilterVisible: false,
        index: -1,
        dispatched: true,
        formData: {
          orderdate: '',
          ordercode: '',
          mordercode: '',
          type: '1',
          buyerinfo: {},
          saleman: '',
          buyer: "",
          mobile: '',
          region_ids: [],
          region_values: [],
          address: '',
          client: '',
          clientname: '',
          ordermemo: '',
          suprate: 0,
          goods: [],
          supmemo: '',
          supid: -1,
          supname: '',
          platformid: -1,
          platform: '',
          platformrate: 0,
          platformratememo: '',
        },
        sum_order: 0,
        sum_sup: 0,
        sum_platform: 0,
        platformid: 1,
        platform: '',
        platforms: [],

        rules: {
          ordercode: [{
            required: true,
            message: "请正确填写订单编号!",
            trigger: 'blur'
          }],
          orderdate: [{
            required: true,
            message: "请填正确填写下单时间!",
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: "请填正确填写下单类型!",
            trigger: 'blur'
          }],
          saleman: [{
            required: true,
            message: "请填写实际客户!",
            trigger: 'blur'
          }],
          buyerinfo: [{
            required: true,
            type: 'object',
            message: "请填正确填写收货人!",
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: "请填正确填写联系电话!",
            trigger: 'blur'
          }],
          region_ids: [{
            type: 'array',
            required: true,
            message: "请选择区域",
            trigger: 'change'
          }],
          address: [{
            required: true,
            message: "请填正确填写详细收货地址!",
            trigger: 'blur'
          }],
          supname: [{
            required: true,
            message: "请填为订单指定供应商!",
            trigger: 'blur'
          }],
          client: [{
            required: true,
            message: "客户名称!",
            trigger: 'blur'
          }],
          suprate: [{
              required: true,
              message: "请填写合适折扣率!",
              trigger: 'blur'
            },
            {
              validator: validatejdrate,
              trigger: 'blur'
            }
          ],
        },
        salelist: [],
        suppliers: [],
        regionList: [],
        tableData: [],
        dialogVisible: true,
        clients: []
      }
    },
    methods: {
      /**合同上传相关回调*/
      /***********************文件上传区域开始****************/
      //文件数量超限提示
      handleLimit: function() {
        this.$message.warning("最多可上传" + this.upconfig.limit + "个文件");
      },
      handleChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png', "pdf"];
        var sizeok = file.size / 1024 / 1024 < 5;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过5M");
          this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
          return;
        }

        this.upconfig.fileList = list;
      },
      // 文件列表移除文件时的钩子
      handleRemove: function(file, fileList) {
        if (file.id) { //如果存储 id即为已经上传好的图片
          this.upconfig.rids.push(file.id);
        }
        this.upconfig.fileList = fileList;
      },
      handlePreview(file) {
        console.log('预览文件', file);
      },

      //-------------------------------------------------------------------------------------合同上传回调结束
      init() {
        this.formData = {
          orderdate: '',
          ordercode: '',
          mordercode: '',
          type: '1',
          buyerinfo: {},
          saleman: '',
          buyer: "",
          mobile: '',
          region_ids: [],
          region_values: [],
          address: '',
          client: '',
          clientname: '',
          ordermemo: '',
          suprate: 0,
          goods: [],
          supmemo: '',
          supid: localStorage.getItem("supid"),
          supname: localStorage.getItem("supname"),
          platformid:-1,
          platformrate: 0,
          platformratememo: '',
        };
        this.formData.tableData = [];
        this.formData.goods = [];
        this.upconfig.fileList = [];
        this.upconfig.imgList = [];

        this.axios.post("/api/admin/platform/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.platforms = res.data.platforms;
            if (this.platforms.length > 0) {
              this.formData.platformid = this.platformid = this.platforms[0].id;
              this.formData.platform = this.platform = this.platforms[0].label;
              this.formData.platformrate = this.platformrate = this.platforms[0].rate;
              console.log('update load');

              this.loadSupRate();

            }
          }
        })


        this.loadSuppliers();
        this.loadClient();
        this.loadRegions();
        this.loadSalemans();
      },
      loadPlatforms: function() {
        this.axios.post("/api/admin/platform/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.platforms = res.data.platforms;
            if (this.platforms.length > 0) {
              this.formData.platformid = this.platformid = this.platforms[0].id;
              this.formData.platform = this.platform = this.platforms[0].label;
              this.formData.platformrate = this.platformrate = this.platforms[0].rate;
              console.log('update load');

            }
          }
        })
      },
      handleImportGood() {
        this.goodfilterVisible = true;
        this.$nextTick(() => {
          this.$refs.goodFilterUI.dialogVisible = true;
          this.$refs.goodFilterUI.initPlatform(this.formData.platformid, this.formData.platform);
        })

      },
      handleRemoveGood(index, row) {
        this.tableData.splice(index, 1);
        this.handleUpdateRmb();
      },
      handleGoodSelect: function(selection) {
        console.log(selection);
        //处理已经选择商品
        selection.forEach(item => {
          var g = {
            did: -1,
            sn: item.sn,
            title: item.title,
            model: item.model,
            brand: item.brand,
            unit: item.unit,
            price: parseFloat(item.price),
            supid: this.formData.supid,
            supname: this.formData.supname,
            suprate: this.formData.suprate,
            platformid: this.platformid,
            platform: this.platform,
            platformrate: this.formData.platformrate,
            count: 1
          }
          this.tableData.push(g)
        })

        this.handleUpdateRmb();
      },
      handleImportBoughtGood() {
        this.buylistVisible = true;
        this.$nextTick(() => {
          this.$refs.buylistUI.dialogVisible = true;
          this.$refs.buylistUI.initData();
        })
      },
      handleImportBoughtGoodCallback(selection){
        console.log(selection);
        //处理已经选择商品
        selection.forEach(item => {
          var g = {
            did: -1,
            sn: item.sn,
            title: item.title,
            model: item.model,
            brand: item.brand,
            unit: item.unit,
            price: parseFloat(item.price),
            supid: this.formData.supid,
            supname: this.formData.supname,
            suprate: this.formData.suprate,
            platformid: this.platformid,
            platform: this.platform,
            platformrate: this.formData.platformrate,
            count: 1
          }
          this.tableData.push(g)
        })
        this.handleUpdateRmb();
      },
      querySearchAsync(str, cb) {
        this.axios.post("api/admin/clientuser/filter", {
          username: str
        }).then(res => {
          if (res.data.code) {
            cb(res.data.data);
          }
        })
      },
      loadSalemans() {
        this.axios.post("api/admin/mate/list_op").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.salelist = res.data.list;
          }
        })
      },

      loadClient() {
        this.axios.post("api/admin/clientuser/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.clients = res.data.list;
          }
        })
      },
      handleClientChanged(item) {
        console.log(item);
        if (item == "") {
          this.formData.buyer = this.formData.address = this.formData.mobile = "";
          this.formData.region_ids = [];
          this.formData.region_values = [];
        } else {
          if (typeof(item) != "string") {
            this.formData.buyer = item.value.username;
            this.formData.region_ids = item.value.region_ids;
            this.formData.region_values = item.value.region_values;
            this.formData.address = item.value.address;
            this.formData.mobile = item.value.mobile;
            this.formData.clientuser = item.value.username;
            this.formData.clientname = item.value.company;
            this.formData.client=item.value.username;
          } else {
            this.formData.buyer = item;
          }
        }
      },
      handleRegionChange: function(reg) {
        this.formData.region_ids = reg;
        this.formData.region_values = this.$refs["cityregion"].getCheckedNodes()[0].pathLabels;
      },
      loadRegions: function() {
        this.axios.post("api/common/region/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.regionList = res.data.data;
          }
        })
      },
      loadSuppliers: function() {
        this.axios.post("api/admin/supplier/list").then((res) => {
          if (res.status == 200 && res.data.code == 0) {
            this.suppliers = res.data.list;
          }
        });
      },

      handleSupChange: function(sup) {
        var option = this.suppliers.filter(function(cur, index, a) {
          if (cur.name == sup) {
            return cur;
          }
        })[0];
        this.formData.supid = option.id;
        this.formData.supname = option.name;

        this.loadSupRate();

      },

      loadSupRate() {
        //根据渠道获取客户对应的点位
        this.axios.post("/api/admin/supplier/getrate", {
          supid: this.formData.supid,
          platform: this.formData.platform
        }).then((res) => {
          if (res.status == 200 && res.data.code == 1) {
              this.$message.success("供应商点位刷新成功");
            this.formData.suprate = res.data.rate;
            this.formData.supratememo = res.data.ratememo;
          } else {
            this.$message.error("获取供应商点位失败，采用默认点位");
            this.formData.suprate = res.data.rate;
            this.formData.supratememo = res.data.ratememo;
          }
          this.handleUpdateRmb();
        })
      },

      handlePlatformChange(platformid) {
        console.log(platformid);
        var option = this.platforms.filter(function(cur, index, a) {
          if (cur.id == platformid) {
            return cur;
          }
        })[0];
        this.platformid = this.formData.platformid = option.id;
        this.platform = this.formData.platform = option.label;
        this.formData.platformrate = option.rate;
        this.formData.platformratememo = option.ratememo;
        console.log(this.formData);
        this.loadSupRate();
        this.handleUpdateRmb();
      },

      format2Number(value, len) {
        var f = parseFloat(value);
        var f = Math.round(value * 10000) / 10000;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
          rs = s.length;
          s += '.';
        }
        while (s.length <= rs + len) {
          s += '0';
        }
        return s;
        return realVal;
      },
      handleUpdateRmb: function() {
        this.sum_order = 0;
        this.sum_sup = 0;
        this.sum_platform = 0;
        this.tableData.map((item) => {
          item.price = parseFloat(item.price + "");
          item.total = item.price * item.count;



          item.platformid = this.platformid;
          item.platform = this.platform;
          item.platformrate = this.platformrate;
          item.ptprice = item.price * this.formData.platformrate;
          item.pttotal = item.ptprice * item.count;

          item.supid = this.formData.supid;
          item.supname = this.formData.supname;
          item.suprate = this.formData.suprate;
          item.supprice = item.price * this.formData.suprate;
          item.suptotal = item.supprice * item.count;
          item.ordercode = this.formData.ordercode;
          item.brand = item.brand;
          item.model = item.model;

          this.sum_order += item.total;
          this.sum_sup += item.suptotal;
          this.sum_platform += item.pttotal;
        })

        this.tableData = JSON.parse(JSON.stringify(this.tableData));
      },
      handleSave: function() {
        this.formData.goods = this.tableData;


        this.$refs.formData.validate(ok => {
          if (ok) {

            //检验合同明细是否正确
            let index = 1;
            let verifyOk = true;
            for (var i = 0; i < this.formData.goods.length; i++) {
              index = (i + 1);
              if (this.formData.goods[i].title == "") {
                this.$message.error({
                  message: '第' + index + "行 商品名称填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].unit == "") {
                this.$message.error({
                  message: '第' + index + "行 计量单位填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].count == "" || this.formData.goods[i].count == "") {
                this.$message.error({
                  message: '第' + index + "行 采购数量填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              }
            }

            if (!verifyOk) {
              return;
            }



            var fd = new FormData();
            fd.append("orderdate", this.formData.orderdate);
            fd.append("ordercode", this.formData.ordercode);
            fd.append("platformid", this.formData.platformid);
            fd.append("platform", this.formData.platform);
            fd.append("platformrate", this.formData.platformrate);
            fd.append("supid", this.formData.supid);
            fd.append("supname", this.formData.supname);
            fd.append("suprate", this.formData.suprate);
            fd.append("supratememo", this.formData.supratememo);
            fd.append("region_ids", JSON.stringify(this.formData.region_ids));
            fd.append("region_values", JSON.stringify(this.formData.region_values));
            fd.append("buyer", this.formData.buyer);
            fd.append("mobile", this.formData.mobile);
            fd.append("address", this.formData.address);
            fd.append("ordermemo", this.formData.ordermemo);
            fd.append("saleman", this.formData.saleman);
            fd.append("clientname", this.formData.clientname);
            fd.append("client", this.formData.client);
            fd.append("sum_order", this.sum_order.toFixed(4));
            fd.append("sum_platform", this.sum_platform.toFixed(4));
            fd.append("sum_sup", this.sum_sup.toFixed(4));
            fd.append("goods", JSON.stringify(this.tableData));

            //附件上传
            let fid = 0;
            this.upconfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("file" + fid, file.raw);
                fid++;
              }
            });


            this.$axiosUploader.post("api/admin/order/create", fd).then(res => {
              if (res.status == 200 && res.data.code == 1) {
                this.$message({
                  message: "创建订单成功!",
                  showClose: true,
                  type: 'success',
                  duration: 1000
                });
                this.$emit("updated");
                this.dialogVisible = false;
              } else {

                this.$message({
                  message: "创建订单失败!" + res.data.msg,
                  showClose: true,
                  type: 'error',
                  duration: 1000
                });
              }
            });
          }
        });
      }
    }
  }
</script>

<style>
</style>
